package com.neu.service.imp;

import com.neu.bean.User;
import com.neu.mapper.UserMapper;
import com.neu.service.UserService;
import com.neu.utils.AjaxResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by dllo on 18/3/12.
 */
@Service
public class UserServiceImp implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        userMapper.add(user);
    }

    @Override
    public AjaxResult reg(String uname, String password, String tel) {
        User user = new User(uname, password, tel);
        AjaxResult result = new AjaxResult();
        if (!userAtgs(user)) {
            result.setCode("0");
            result.setMsg("注册失败");
            return result;
        }
        else if (userExist(uname)) {
            result.setCode("0");
            result.setMsg("注册失败");
            return result;
        } else {
            register(user);
            System.out.println("用户注册：" + user.getUname() + user.getPassword());
            result.setCode("1");
            result.setMsg("注册成功");
            result.setData(user);
            System.out.println(result);
            return result;
        }

    }

    // 判断用户是否已经存在
    @Override
    public boolean userExist(String username) {
        return userMapper.userExist(username) > 0;
    }

    // 判断参数是否合法
    private boolean userAtgs(User user) {
        if (user.getUname() == null || user.getUname().length() == 0) {
            return false;
        }
        if (user.getPassword() == null || user.getPassword().length() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public User login(String name, String password) {
        User user = userMapper.findalluser(name, password);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }
}
